package com.framework.modules.job.task;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.framework.entity.aliPay.AliPayConfig;
import com.framework.entity.flow.FlowTask;
import com.framework.entity.sys.SysDept;
import com.framework.entity.sys.SysDict;
import com.framework.entity.sys.SysPayment;
import com.framework.service.*;
import com.framework.utils.ali.AliPay;
import com.framework.utils.pay.youfupay.entity.PaymentTransQueryModle;
import com.framework.utils.pay.youfupay.method.PaymentQueryMethod;
import com.framework.utils.pay.yunzhanghujiesuan.YunJieSuanPay;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 修改提现
 */
@Component("updateKayiTakeState")
public class UpdateKayiTakeState {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private FlowTaskService flowTaskService;
    @Autowired
    private TranOrderService tranOrderService;
    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private DeptService deptService;

    @Autowired
    private DictService dictService;

    public void updateKayiTakeState() {
        //查询需要修改订单的相关信息
        logger.info("-----------------修改卡一提现信息开始---------------------");
        //支付宝
        List<String> list = flowTaskService.queryExamineTake(889323L, 3);
        AliPayConfig aliPayConfig = tranOrderService.queryAliPayConfig(889323L);
        Map<String, Object> result;
        for (String takeNo : list) {
            result = AliPay.aLiTransferQuery(aliPayConfig, takeNo);
            handleAliPayResult(result, takeNo);
        }
        logger.info("-----------------修改卡一提现信息成功---------------------");
    }

    private void handleAliPayResult(Map<String, Object> result, String takeNo) {

        if (result == null) {
            logger.info("----------支付宝未查询到订单号为" + takeNo + "的信息--------------");
            return;
        }
        String status = result.get("code").toString();
        if ("INIT".equals(status) || "DEALING".equals(status)) {
            return;
        }
        FlowTask flowTask = flowTaskService.queryFlowTaskByNo(takeNo);
        if (flowTask == null) {
            logger.info("----------未查询到订单号为" + takeNo + "的订单提现---------------");
        }
        Long agentId = flowTask.getAgentId();
        //支付宝订单状态 SUCCESS：成功 FAIL：失败  INIT：等待处理  DEALING：处理中  REFUND：退票 UNKNOWN：未知
        //处理 成功，失败，退票，未知，其余不处理
        if ("SUCCESS".equals(status)) {
            flowTask.setTaskState("SUCCESS");
            flowTask.setExplains("提现成功");
            agentInfoService.reduceFreeznAmount(agentId, flowTask.getTakeAmount());
        } else {
            flowTask.setTaskState("FAILURE");
            flowTask.setExplains("提现失败" + result.get("msg").toString());
            //返还金额
            agentInfoService.addBalance(agentId, flowTask.getTakeAmount());
        }
        flowTaskService.updateById(flowTask);
    }

    public void updateBaiyiTakeState() throws Exception {
        List<SysDept> list = deptService.getDeptListExcept(0L);
        for (SysDept sysDept : list) {
            updateTakeState(sysDept);
            updateyoufuTakeState(sysDept);
        }
    }

    public void updateTakeState(SysDept sysDept) throws Exception {
        //查询需要修改订单的相关信息
        logger.info("-----------------修改" + sysDept.getName() + "提现信息开始---------------------");
        //云账户
        List<String> list = flowTaskService.queryExamineTake(sysDept.getDeptId(), 4);
        SysPayment payment = paymentService.queryPaymentByDeptId(sysDept.getDeptId());
        if(payment==null){
            return;
        }
        if(payment.getPayType().intValue()==4){
            Map<String, Object> result;
            for (String takeNo : list) {
                result = YunJieSuanPay.queryOrder(takeNo, payment);
                handleYunjiesuanResult(result, takeNo);
            }
        }

        logger.info("-----------------修改" + sysDept.getName() + "提现信息成功---------------------");
    }


    private void handleYunjiesuanResult(Map<String, Object> result, String takeNo) {
        if (result == null) {
            logger.info("----------云账号未查询到订单号为" + takeNo + "的信息--------------");
            return;
        }
        System.out.println(result);
        String code = result.get("code").toString();
        if (!"0000".equals(code)) {
            logger.info("-------订单号为:" + takeNo + "错误信息为" + result.get("message") + "----------");
        }
        Map<String, Object> data = (Map<String, Object>) result.get("data");
        String status = data.get("status").toString();
        FlowTask flowTask = flowTaskService.queryFlowTaskByNo(takeNo);
        Long agentId = flowTask.getAgentId();
        if (flowTask == null) {
            logger.info("----------未查询到订单号为" + takeNo + "的订单提现---------------");
        }
        if ("1".equals(status)) {
            flowTask.setTaskState("SUCCESS");
            flowTask.setExplains("提现成功");
            agentInfoService.reduceFreeznAmount(agentId, flowTask.getTakeAmount());

        } else if ("2".equals(status) || "9".equals(status)) {
            flowTask.setTaskState("FAILURE");
            flowTask.setExplains("提现失败---" + data.get("status_detail_message").toString());
            //返还金额
            agentInfoService.addBalance(agentId, flowTask.getTakeAmount());
            //取消支付
        } else if ("15".equals(status)) {
            flowTask.setTaskState("FAILURE");
            flowTask.setExplains("提现失败---" + data.get("status_detail_message").toString());
            //返还金额
            agentInfoService.addBalance(agentId, flowTask.getTakeAmount());
        }
        flowTaskService.updateById(flowTask);


    }


    public void updateyoufuTakeState(SysDept sysDept) {
        //查询需要修改订单的相关信息
        logger.info("-----------------修改" + sysDept.getName() + "提现信息开始---------------------");
        //优付代付
        List<FlowTask> list = flowTaskService.queryExamineTakeList(sysDept.getDeptId(), 5);
        SysPayment payment = paymentService.queryPaymentByDeptId(sysDept.getDeptId());
        if(payment==null){
            return;
        }
        if(payment.getPayType().intValue()!=5){
            return;
        }
        SysDict secretKey = dictService.querySysDict(sysDept.getDeptId().intValue(), "1", "pay_secret_key");
        for (FlowTask flowTask : list) {

            PaymentTransQueryModle model = PaymentQueryMethod.paymentQuery(payment, flowTask.getTakeNo(), flowTask.getBatchId(), secretKey.getValue());

            List<PaymentTransQueryModle.QueryItems> queryItems = model.getQueryItems();

            PaymentTransQueryModle.QueryItems queryItem = queryItems.get(0);
            if (queryItem.getState() == 3) {
                flowTask.setTaskState("success");
                flowTask.setExplains("提现成功");
            } else if (queryItem.getState() == 4) {
                flowTask.setTaskState("fail");
                flowTask.setExplains("提现失败--信息不正确");
            }
            flowTaskService.updateById(flowTask);
        }


        logger.info("-----------------修改" + sysDept.getName() + "提现信息成功---------------------");
    }


}